#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <MQTTClient.h>

#define MQTT_BROKER_ADDRESS "tcp://mqtt.broker.com" // 替换为您的 MQTT 代理地址
#define MQTT_TOPIC "mytopic" // 替换为您的 MQTT 主题

volatile int message_received = 0;

void messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message) {
    printf("Received MQTT message: %.*s\n", message->payloadlen, (char *)message->payload);
    message_received = 1;
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
}

int main(int argc, char *argv[]) {
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

    // 初始化 MQTT 客户端
    MQTTClient_create(&client, MQTT_BROKER_ADDRESS, "ExampleClient", MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    // 连接到 MQTT 代理
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS) {
        printf("Failed to connect to MQTT broker\n");
        return -1;
    }

    // 订阅主题
    MQTTClient_subscribe(client, MQTT_TOPIC, 0);

    // 循环等待接收消息
    while (!message_received) {
        // 等待消息到达
    }

    // 断开连接
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
}